package util.benchmark;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;

public class BenchMarker {
	static private Map<String, Clock> clocks = new HashMap<String, Clock>();
	static private Map<String, Counter> counters = new HashMap<String, Counter>();

	/**
	 * 名字应该取成类似包名的用"."分隔的结构
	 * @param name
	 * @return
	 */
	public static Counter getCounter(String name) {
		Counter counter = counters.get(name);
		if (counter != null)
			return counter;
		counter = new Counter();
		counters.put(name, counter);
		return counter;
	}
	
	/**
	 * 名字应该取成类似包名的用"."分隔的结构
	 * @param name
	 * @return
	 */
	public static Clock getClock(String name) {
		Clock clock = clocks.get(name);
		if (clock != null)
			return clock;
		clock = new Clock();
		clocks.put(name, clock);
		return clock;
	}
	
	/**
	 * 生成最终的文本化报告
	 * @return
	 */
	public static String getTextReport() {
		StringBuilder sb = new StringBuilder();
		sb.append("--------------- Benchmark -------------\n");
		sb.append("Counters: \n\n");
		for (Entry<String, Counter> entry : counters.entrySet()) {
			sb.append(String.format("%s %10d\n", 
					fillStr(entry.getKey(), 32, '.'), entry.getValue().getCount()));
		}
		sb.append("\nClocks: \n\n");
		for (Entry<String, Clock> entry : clocks.entrySet()) {
			Clock clock = entry.getValue();
			// String name = entry.getKey();
			sb.append(String.format("%s %10d ［%10dms］\n", 
					fillStr(entry.getKey(), 32, '.'), clock.getCount(), clock.getTotalTime()));
		}
		return sb.toString();
	}
	
	/**
	 * 利用靠左的方式填充字符串
	 * @param src
	 * @param len
	 * @param c 
	 * @return
	 */
	private static Object fillStr(String src, int len, char c) {
		StringBuilder sb = new StringBuilder(src);
		for (int i = 0; i < len - src.length(); i++) {
			sb.append(c);
		}
		return sb.toString();
	}

	/**
	 * For Test purpose only
	 * @param args
	 */
	public static void main(String[] args) {
		Random rand = new Random();
		Counter[] counters = new Counter[10];
		Clock[] clocks = new Clock[10];
		for (int i = 0; i < 10; i++) {
			counters[i] = BenchMarker.getCounter("counter-" + i);
			clocks[i] = BenchMarker.getClock("clock-" + i);
			clocks[i].start();
		}
		for (int i = 0; i < 10000; i++) {
			counters[rand.nextInt(10)].inc();
			clocks[rand.nextInt(10)].inc();
		}
		for (int i = 0; i < 10; i++) {
			int idx = rand.nextInt(10);
			if (rand.nextInt(2) == 1)
				clocks[idx].pause();
			else 
				clocks[idx].cont();
			try {
				System.out.println(i);
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(BenchMarker.getTextReport());
	}
}
